<?php
namespace App\Models\User;
use App\Libs\Base\Constant;
use App\Libs\Helper\CommonHelper;
use App\Models\Goods\Goods;
class User extends \App\Libs\Base\BaseModel
{
    protected $__TABLE__ = 't_paile_user_info';
	protected static $salt = 'Just-4#Holp';
    private function generate($identify) {
        return  md5(md5($identify . ':' . mt_rand(1, 1000)) . microtime(true));
    }
	
	/**
	*	跳过检测了
	*/
	public function beforeValidation()
	{
	  self::skipValidation(['utime','username','avatar','credential_type','credential_no','email','unionid','openid','baby_name','baby_sex','baby_birthday'] , $this );
	}
	
	/**
	*	注册
	*/
    public function regist($infos) {
		// phone is not regist
		
		/*$params = array(
			'phone = ?0',
			'bind' => array($infos['phone']),
		);
		if (self::find($params)) {
			return -1;
		}
		// username is unique
		$params = array(
			'username = ?0',
			'bind' => array($infos['username']),
		);
		if (self::find($params)) {
			return -2;
		}*/

        $token = $this->getUniqueToken($infos);

        $infos['token'] = $token;
        $infos['ctime'] = date('Y-m-d H:i:s');
		$infos['username'] = \App\Libs\Helper\CommonHelper::randomChat();
		$infos['avatar'] = \App\Libs\Base\Config::instance()->common['commonAvatar'];
		$infos['baby_name'] = '';
		$infos['baby_sex'] = '0';
		$infos['baby_birthday'] = '';
        //$infos['password'] = md5($infos['password'] . ':' . self::$salt);

		unset($infos['id']);
		foreach ($infos as $field => $value) {
			$this->{$field} = $value;
		}

		$this->save();
		\App\Libs\Session\Session::regist($this);
		return $this->id;
    }
	
	/**
	*	登录密码
	*/
	public function login($password) {
		$isfit = md5($password . ':' . self::$salt) === $this->password;
		if ($isfit) {
			// set session
			\App\Libs\Session\Session::regist($this);
		}

		return $isfit;
	}	

	/**
	*	检查验证码
	*/
	public function loginCaptcha($captcha) {
		$key = 'captcha:' . $this->phone;
		if( $this->phone != '13783032783' ){
			$store = \App\Libs\Cache\Redis::get($key);
		}else{
			$store = '1234';
		}
		if ($store === strtolower($captcha)) {
			if (isset($this->id)) {
				\App\Libs\Session\Session::regist($this);
			}
			return TRUE;
		}

		return FALSE;
	}

    public function getUniqueToken($info) {
        // generate token
        $identify = '';
        if (!empty($info['phone'])) {
            $identify = $info['phone'];
        } else if (!empty($info['wx_unionid'])) {
            $identify = $info['wx_unionid'];
        } else {
            $identify = $info['username'];
        }
		$retry = 5;
        do {
            $token = $this->generate($identify);

            $isExist = self::getUserByToken($token);

			if ($retry <= 0) {
				throw \App\Libs\Exception\RuntimeException::instance(Constant::RESOURCE_MISSING);
			}
			$retry --;
        } while($isExist);

        return $token;
    }

    public static function getUserByToken($token) {
		return self::find(array(
			'token = ?0',
			'bind' => array($token),
		));
    }


    public function getUserInfo($userIdAray)
    {
        $userInfo = self::findAll([
            'conditions' => 'id IN ({userIdAray:array})',
            'columns' => 'id as uid,username,avatar',
            'bind' => ['userIdAray' => $userIdAray]
        ])->toArray();
        return $userInfo;
    }

    /**
     *      合并用户的信息和他们的评论
     * @param $user  用户id数组
     * @param $userCmt   用户评论数组
     * @return array  合并后的数据
     */
    public function mergeUfoAndCmt($user, $userCmt)
    {
        $userInfo = $this->getUserInfo($user);
        $topUserInfo = CommonHelper::setColToKey($userInfo, 'uid');
       	$cmtAndUserInfo = [];
	 foreach ($userCmt as $key => $val) {
            if(isset($topUserInfo[$userCmt[$key]['uid']])){
                $cmtAndUserInfo[] = array_merge($userCmt[$key], $topUserInfo[$userCmt[$key]['uid']]);
            }
        }
        return $cmtAndUserInfo;
    }

    public function afterFetch()
    {
	$this->balance_num = $this->balance;
        $this->balance = Goods::formatPrice($this->balance);
    }
	
}
